<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>获取路径</title>
  <link rel="stylesheet" href="http://minedata.cn/minemapapi/v1.1/minemap.css">
  <script src="http://minedata.cn/minemapapi/v1.1/minemap.js"></script>
  <script src="http://minedata.cn/minemapapi/demo/js/MapXMLHttpRequest.js"></script>
  <style>

    html, body, #map {
      width: 100%;
      height: 100%;
    }

    html, body {
      margin: 0;
      padding: 0;
    }

    .distance-container {
      position: absolute;
      top: 10px;
      left: 10px;
      z-index: 1;
    }

    .distance-container > * {
      background-color: rgba(0, 0, 0, 0.5);
      color: #fff;
      font-size: 11px;
      line-height: 18px;
      display: block;
      margin: 0;
      padding: 5px 10px;
      border-radius: 3px;
    }

  </style>
</head>

<body>
<div id='map'></div>
<div id='distance' class='distance-container'></div>

<script>
  minemap.accessToken = '0b871b483cfb42a7b0dd73b5f78792e8';
  minemap.solution = 66;
  var map = new minemap.Map({
    container: 'map',
    style: "http://minedata.cn/service/solu/style/id/66",
    center: [109.850705, 40.657452],
    zoom: 12,
    pitch: 0
  });
  map.on("load",function () {
    map_init()
  })


  var chosedPoints = []
  var distanceContainer = document.getElementById('distance');

  var route_geojson = {
    "type": "geojson",
    "data": {
      "type": "FeatureCollection",
      "features": []
    }
  };
  var myHttp = new MapXMLHttpRequest()


  /**
   * 获取两点之间的行驶路径
   * @param sPoint 起点经纬度 ：“经度,纬度”
   * @param ePoint 终点经纬度 ： 同上
   * @param wayPoints 途经点的经纬度：默认为无
   */
  function getRoute(sPoint,ePoint,wayPoints) {
    var url_head = "http://123.207.124.207:8084/minemap-server/service/route/driving?&token=123444&"
      // sPoint=109.83611583709717,40.607355154008985
    // &ePoint=109.86656427383423,40.65546781426045
    // &wayPoints=109.82500076293945,40.6212168482447
    var costModel=32 // 不考虑动态交通的最短距离
    var url = url_head+"sPoint="+sPoint+"&ePoint="+ePoint+"&wayPoints="+wayPoints+"&costModel="+costModel
    myHttp.send("GET", url, '', callback, null)

  }


  function callback(responseText, responseXML) {
    //{"errcode":0,"errmsg":null,"data":{"pageCount":0,"totalCount":0,"pageNumber":0,"rows":[]}}
    var searchResult = {}
    if (responseText.length > 1) {
      searchResult = JSON.parse(responseText)
      if (searchResult.errcode == 0 && searchResult.data.rows.length > 0) {
        console.log("get call back")
        console.log(searchResult)
        var resGeojson = translateRes2Geojson(searchResult)
        console.log(resGeojson)
      }
    }
  }
  function translateRes2Geojson(response) {
    response.data.rows[0].segmt.forEach(function (line) {
      var lineSegment = {
        "type": "Feature",
        "geometry": {
          "type": "LineString",
          "coordinates": []
        },
        "properties": {
          "roadName":'',
          "dist":'',
          "distUnit":''
        }
      }

      lineSegment.geometry = line.clist.geometry
      lineSegment.properties.roadName = line.roadName
      lineSegment.properties.dist = line.dist.dist
      lineSegment.properties.distUnit = line.dist.unit
      poi.properties = point;
      route_geojson.data.features.push(lineSegment)

      return lineSegment
    })

    console.log(route_geojson)
    return route_geojson
    map.getSource("patrol_route").setData(route_geojson)
  }


  function pushPointFeatures(e,features) {

    //过滤掉id和输入的feature相同的数据
    if (features.length) {
      var id = features[0].properties.id;
      this.route_geojson.data.features =  this.route_geojson.data.features.filter(function (point) {
        return point.properties.id !== id;
      });
    } else {
      var pointGeojson = {
        "type": "Feature",
        "geometry": {
          "type": "Point",
          "coordinates": [
            e.lngLat.lng,
            e.lngLat.lat
          ]
        },
        "properties": {
          "id": String(new Date().getTime())
        }
      };
      //给点坐标集合增加元素
      this.route_geojson.data.features.push(pointGeojson);
    }

    replan_route()
  }
  function  replan_route() {
    if(this.route_geojson.data.features.length>1){
      for(i=0; i<this.route_geojson.features.length; i++){
        var startPoint = this.route_geojson.data.features[i].geometry.coordinates
        var endPoint = this.route_geojson.data.features[i+1].geometry.coordinates
        getRoute(startPoint,endPoint)
      }
    }
  }


  function map_init() {
   map.addSource("patrol_route_source", route_geojson)

   map.addLayer({
     "id": "route_lines",
     "type": "line",
     "source": "patrol_route_source",
     "layout": {
       "line-join": "round",
       "line-cap": "round"
     },
     "paint": {
       "line-color": "#ff0000",
       "line-width": 6
     }
   });

   map.addLayer({
     "id": "route_points",
     "type": "symbol",
     "source": "patrol_route_source",
     "layout": {
       "icon-image": "circle-stroked-11",
     },
     "paint": {
       "icon-color": "#0000ff"
     }
   });
 }


  //click后：判断某点是否已经存在，若存在就删除,否则增加该点
  map.on('click', function (e) {
    var features = map.queryRenderedFeatures(e.point, {layers: ['route_points']});
    pushPointFeatures(e,features)
  });

  map.on('mousemove', function (e) {
    var features = map.queryRenderedFeatures(e.point, {layers: ['measure-points']});
    map.getCanvas().style.cursor = (features.length) ? 'pointer' : 'crosshair';
  });

  document.getElementById("map").addEventListener("contextmenu", function () {
    route_geojson = {
      "type": "geojson",
      "data": {
        "type": "FeatureCollection",
        "features": []
      }
    };
    document.getElementById("distance").innerHTML = "数据已清空";

  });
</script>

</body>
</html>

